package com.aplink.generic.adapter;

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import com.aplink.generic.GenericFragment;
import com.aplink.generic.dictionary.GenericDictionary;
import com.aplink.generic.pojo.PageItem;
import com.aplink.generic.pojo.controlspec.viewpager.ViewPagerSpec;

public class ViewPagerAdapter extends FragmentPagerAdapter {
    private final GenericDictionary<String, GenericFragment> mFragmentList;
    private final ViewPagerSpec mViewPagerFormat;

    public ViewPagerAdapter(final FragmentManager fm,
            final ViewPagerSpec viewPagerFormat) {
        super(fm);
        this.mViewPagerFormat = viewPagerFormat;
        this.mFragmentList = new GenericDictionary<String, GenericFragment>();
    }

    @Override
    public int getCount() {
        return this.mViewPagerFormat.getPageCollection().size();
    }

    public final GenericDictionary<String, GenericFragment> getFragments() {
        return mFragmentList;
    }

    @Override
    public GenericFragment getItem(final int arg0) {
        final PageItem pageItem = this.mViewPagerFormat.getPageCollection()
                .get(arg0);
        final String className = pageItem.getName();
        if (!this.mFragmentList.containsKey(className)) {
            final GenericFragment genericFragment = GenericFragment
                    .newInstance(pageItem.getFormDesignID(),
                            pageItem.getContentDataID());
            this.mFragmentList.put(className, genericFragment);
        }
        return this.mFragmentList.get(className);
    }

    @Override
    public CharSequence getPageTitle(final int position) {
        final PageItem pagerItem = this.mViewPagerFormat.getPageCollection()
                .get(position);
        return pagerItem.getTitle();
    }
}
